<template>
  <el-card class="submissions-card">
    <template #header>
      <div class="header">
        <span>作业提交情况</span>
      </div>
    </template>

    <el-table
      v-loading="loading"
      :data="submissionList"
      empty-text="暂无提交记录"
      stripe
      style="width: 100%"
    >
      <el-table-column label="学号" prop="studentId" width="100" />
      <el-table-column label="姓名" prop="studentName" width="150" />
      <el-table-column label="状态" prop="status" width="150">
        <template #default="{ row }">
          <el-tag :type="statusTagType(row.status)">
            {{ statusLabel(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="提交时间" prop="submissionDate" width="200">
        <template #default="{ row }">
          <span>{{ formatDate(row.submissionDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分数" prop="score" width="220">
        <template #default="{ row }">
          <div v-if="row.status === 'GRADED'">
            {{ row.score }}
          </div>
          <div
            v-else-if="row.status === 'SUBMITTED'"
            style="display: flex; align-items: center; gap: 8px"
          >
            <el-input-number
              v-model="row.tempScore"
              :max="100"
              :min="0"
              size="small"
              style="width: 100px"
            />
            <el-button :loading="row.grading" size="small" type="primary" @click="submitGrade(row)">
              评分
            </el-button>
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="openDetailDialog(row)">
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="dialogVisible"
      :close-on-click-modal="false"
      title="学生作答详情"
      width="70%"
    >
      <div v-if="answerDetailList.length === 0" class="empty-text">暂无答题详情</div>

      <div v-else class="dialog-content-scroll-wrapper">
        <el-collapse v-model="activeNames" accordion>
          <el-collapse-item
            v-for="(item, index) in answerDetailList"
            :key="item.questionId"
            :name="String(item.questionId)"
          >
            <template #title>
              <span>题 {{ index + 1 }}</span>
              <el-tag
                :type="
                  item.type === 'SUBJECTIVE' || item.type === 'FILL_IN_BLANK'
                    ? 'info'
                    : item.isCorrect
                      ? 'success'
                      : 'danger'
                "
                style="margin-left: 10px"
              >
                {{
                  item.type === 'SUBJECTIVE' || item.type === 'FILL_IN_BLANK'
                    ? '待查看'
                    : item.isCorrect
                      ? '正确'
                      : '错误'
                }}
              </el-tag>
            </template>

            <div class="question-detail" style="margin-top: 10px">
              <p>
                <strong>题目内容：</strong>
                <span v-html="renderMarkdown(item.content)"></span>
              </p>
              <p>
                <strong>学生答案：</strong>
                <span v-html="formatAnswer(item.userAnswer, item.type)"></span>
              </p>
              <p>
                <strong>正确答案：</strong>
                <span v-html="formatAnswer(item.correctAnswer, item.type)"></span>
              </p>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>

      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'
import { apiClient, handleErrorAndRedirect } from '@/api'
import { renderMarkdown } from '@/api/utils.ts'

interface StudentAnswerDetail {
  questionId: number
  content: string
  type: string
  correctAnswer: string
  userAnswer: string
  isCorrect: boolean | null
}

const route = useRoute()
const assignmentId = route.params.assignmentId

const submissionList = ref<any[]>([])
const loading = ref(true)

const dialogVisible = ref(false)
const answerDetailList = ref<StudentAnswerDetail[]>([])
const activeNames = ref<string[]>([])

onMounted(async () => {
  try {
    const { data } = await apiClient.get(`/assignments/${assignmentId}/submissions`)
    submissionList.value = data.map((item: any) => ({
      ...item,
      tempScore: item.score || 0,
      grading: false,
    }))
  } catch (error) {
    handleErrorAndRedirect(error, '获取提交列表失败')
  } finally {
    loading.value = false
  }
})

const statusLabel = (status: string): string => {
  switch (status) {
    case 'SUBMITTED':
      return '已提交'
    case 'GRADED':
      return '已评分'
    case 'NOT_STARTED':
      return '未开始'
    default:
      return status
  }
}

const statusTagType = (status: string): string => {
  switch (status) {
    case 'SUBMITTED':
      return 'warning'
    case 'GRADED':
      return 'success'
    case 'NOT_STARTED':
      return 'danger'
    default:
      return ''
  }
}

const formatDate = (dateStr: string): string => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString()
}

const submitGrade = async (row: any): Promise<void> => {
  row.grading = true
  try {
    await apiClient.post(`/assignments/submissions/${row.studentAssignmentId}/grade`, {
      score: row.tempScore,
    })
    row.status = 'GRADED'
    row.score = row.tempScore
    ElMessage.success('评分成功')
  } catch (e: any) {
    console.error(e)
    ElMessage.error('评分失败')
  } finally {
    row.grading = false
  }
}

const openDetailDialog = async (row: any): Promise<void> => {
  try {
    const { data } = await apiClient.get(
      `/assignments/${assignmentId}/submissions/${row.studentId}`,
    )
    answerDetailList.value = data
    activeNames.value = data.length > 0 ? [String(data[0].questionId)] : []
    dialogVisible.value = true
  } catch (error) {
    console.error(error)
    ElMessage.error('加载详情失败')
  }
}

const formatAnswer = (answer: string, type: string): string => {
  if (!answer) return '-'

  try {
    const parsed = JSON.parse(answer)

    if ((type === 'SUBJECTIVE' || type === 'FILL_IN_BLANK') && Array.isArray(parsed)) {
      const imgs = parsed
        .filter((item) => typeof item === 'object' && item.image)
        .map((item) => `<img src="${item.image}" style="max-width: 100%; margin-bottom: 10px;" />`)
      return imgs.length > 0 ? imgs.join('<br/>') : '-'
    }
    if (type === 'SINGLE_CHOICE' || type === 'MULTIPLE_CHOICE') {
      if (typeof parsed === 'object') {
        return Object.values(parsed).join(', ')
      }
    }
  } catch {}

  return answer
}
</script>

<style scoped>
.submissions-card {
  margin: 20px;
}

.header {
  font-size: 18px;
  font-weight: bold;
}

.el-collapse-item {
  margin-bottom: 16px;
}

.el-collapse-item__content {
  height: auto !important;
  max-height: none !important;
  overflow: visible !important;
}

.el-collapse-item__header span {
  display: inline-block;
  word-break: break-word;
  white-space: normal;
}

.question-detail p {
  margin: 6px 0;
  word-break: break-word;
  white-space: normal;
}

.dialog-content-scroll-wrapper {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 10px;
}

.empty-text {
  text-align: center;
  padding: 20px;
  color: #999;
}
</style>
